﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;

namespace XQL
{
    public partial class XQLCreateTable : Form
    {
       // int rowIndex = 0;
        public string CTServerName, CTServerPath, CtTableName;
        public bool Create = true;
        public XQLCreateTable()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (clmNameTxt.Text == "")
            {
                MessageBox.Show("Please enter valid column name");
                return;
            }
            else
            {
                if (clmNameTxt.Text.Contains(' '))
                {
                    MessageBox.Show("Please enter valid column name");
                    return;
                }
            }
            if (dataGridView1.Rows.Count == 0)
            {

                dataGridView1.ColumnCount = 1;
                dataGridView1.Columns[0].Name = "Column Name";
                string[] row = new string[] { clmNameTxt.Text };
                dataGridView1.Rows.Add(row);



            }
            else
            {
                string[] row = new string[] { clmNameTxt.Text };
                dataGridView1.Rows.Add(row);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedCells.Count > 0)
            {
                if (dataGridView1.CurrentRow.Cells[0].Value != null)
                    dataGridView1.Rows.Remove(dataGridView1.CurrentRow);
                
            }
            //if (dataGridView1.SelectedRows.Count > 0)
            //{
            //    foreach (DataGridViewRow dr in dataGridView1.SelectedRows)
            //    {
            //        if (dr == dataGridView1.CurrentRow)
            //        {
            //            dataGridView1.Rows.Remove(dataGridView1.CurrentRow);
            //        }
            //    }
            //}
           
        }

        private void sveBtn_Click(object sender, EventArgs e)
        {
            if (tblNameTxt.Text == "")
            {
                MessageBox.Show("Please enter table name");
                return;
            }
            else
            {
                string TName = tblNameTxt.Text;
                if (TName.Contains(' '))
                {
                    MessageBox.Show("Please enter valid table name");
                    return;
                }
            }
            if (dataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("Table must have minium of one column");
                return;
            }
                string[] ColumnList = new string[dataGridView1.Rows.Count - 1];
                int i;
                for (i = 0; i < dataGridView1.Rows.Count - 1; i++)
                {
                    ColumnList[i] = dataGridView1[0, i].Value.ToString();
                    if(ColumnList[i].Contains(' '))
                    {
                        MessageBox.Show("'" + ColumnList[i] + "' is not a valid column name!");
                        return;
                    }
                }
                if (Directory.Exists(CTServerPath))
                {
                    if (!Create)
                    {
                        if (File.Exists(CTServerPath + "\\" + CtTableName + ".xml"))
                        {
                            File.Delete(CTServerPath + "\\" + CtTableName + ".xml");
                            
                        }
                    }
                    if (!File.Exists(CTServerPath + "\\" + tblNameTxt.Text + ".xml"))
                    {
                        //MessageBox.Show("Folder " + CTServerName + " is present");
                        XmlDocument XmlTable = new XmlDocument();
                        XmlNode RootTableNode;
                        RootTableNode = XmlTable.CreateNode(XmlNodeType.XmlDeclaration, "", "");
                        XmlTable.AppendChild(RootTableNode);
                        XmlElement TableName, RootTable;
                        RootTable = XmlTable.CreateElement("Root" + tblNameTxt.Text);
                        TableName = XmlTable.CreateElement(tblNameTxt.Text);
                        for (i = 0; i < ColumnList.Length; i++)
                        {
                            XmlElement TableColumn = XmlTable.CreateElement(ColumnList[i].ToString());
                            XmlText TableColumnText = XmlTable.CreateTextNode("");
                            TableColumn.AppendChild(TableColumnText);
                            TableName.AppendChild(TableColumn);
                        }
                        RootTable.AppendChild(TableName);
                        XmlTable.AppendChild(RootTable);

                        XmlTable.Save(CTServerPath + "\\" + tblNameTxt.Text + ".xml");
                        if (File.Exists(CTServerPath + "\\" + tblNameTxt.Text + ".xml"))
                        {
                            if (!Create)
                            {
                                MessageBox.Show("Table Updated Successfully!");
                                Create = true;
                            }
                            else
                            {
                                MessageBox.Show("Table Created Successfully!");
                            }
                            this.Close();
                        }
                        else
                        {
                            MessageBox.Show("Table Creation failed!");
                        }
                    }
                    else
                        MessageBox.Show("'" + tblNameTxt.Text + "' , already exists!");
                }
                else
                    MessageBox.Show("Fail!");
            
        }
        public void LoadServerInfo(string ServerName, string ServerPath, bool EditType)
        {
            if (EditType)
            {
                Create = true;
                sveBtn.Visible = true;
                updtTable.Visible = false;
                delTable.Visible = false;
            }
            else
            {
                Create = false;
                sveBtn.Visible = false;
                updtTable.Visible = true;
                delTable.Visible = true;
                delColumn.Visible = false;
            }
            CTServerName = ServerName;
            CTServerPath = ServerPath;
        }

        public bool EditLoadInfo(string TableName)
        {
            tblNameTxt.Text = TableName;
            this.Text = "Edit Table '" + TableName + "'";
            CtTableName = TableName;
            if (TableName == CTServerName)
            {
                MessageBox.Show("Please select a table");
                return false;
            }
            dataGridView1.Rows.Clear();
            if (Directory.Exists(CTServerPath))
            {
                if (File.Exists(CTServerPath + "\\" + CtTableName + ".xml"))
                {
                    XmlDocument XmlTable = new XmlDocument();
                    XmlTable.Load(CTServerPath + "\\" + CtTableName + ".xml");
                    string NodeHier = "Root" + TableName + "/" + TableName;
                    XmlNodeList NodeList = XmlTable.SelectNodes(NodeHier);
                    dataGridView1.ColumnCount = 1;
                    dataGridView1.Columns[0].Name = "Column Name";
                    foreach (XmlNode node1 in NodeList)
                    {
                        foreach (XmlNode node2 in node1)
                        {
                            dataGridView1.Rows.Add(node2.Name);
                        }
                        break;
                    }
                    return true;
                }
                else
                {
                    MessageBox.Show("Table is missing!");
                    return false;
                }
            }
            else
                return false;
        }

        private void XQLCreateTable_Load(object sender, EventArgs e)
        {

        }

        private void updtTable_Click(object sender, EventArgs e)
        {
            Create = false;
            string newTableName = tblNameTxt.Text;
            string[] ColumnList = new string[dataGridView1.Rows.Count - 1];
            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                if (dataGridView1[0, i].Value != null)
                {
                    ColumnList[i] = dataGridView1[0, i].Value.ToString();
                    if (ColumnList[i].Contains(' '))
                    {
                        MessageBox.Show("'" + ColumnList[i] + "' is not a valid column name!");
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("Please enter valid column name!");
                    return;
                }
            }
            if (Directory.Exists(CTServerPath))
            {
                if (File.Exists(CTServerPath + "\\" + CtTableName + ".xml"))
                {
                    XmlDocument XmlTable = new XmlDocument();
                    XmlTable.Load(CTServerPath + "\\" + CtTableName + ".xml");
                    string NodeHier = "Root" + CtTableName + "/" + CtTableName;
                ReloadNode: XmlNodeList NodeList = XmlTable.SelectNodes(NodeHier);
                    int i = 0;
                    int columnCount = 0;
                    int DSize = dataGridView1.Rows.Count - 2;
                    foreach (XmlNode node1 in NodeList)
                    {

                        foreach (XmlNode node2 in node1)
                        {
                            if (i <= DSize)
                            {
                                if (dataGridView1.Rows[i].Cells[0].Value.ToString() != node2.Name.ToString())
                                {
                                    XmlElement currentNode = (XmlElement)node2;
                                    XmlElement newColumn = XmlTable.CreateElement(dataGridView1.Rows[i].Cells[0].Value.ToString());
                                    XmlText newText = XmlTable.CreateTextNode(node2.InnerText);
                                    newColumn.AppendChild(newText);
                                    node1.InsertBefore(newColumn, currentNode);
                                    node1.RemoveChild(currentNode);
                                    goto ReloadNode;

                                }
                            }
                            else
                            {
                                XmlElement currentNode = (XmlElement)node2;
                                node1.RemoveChild(currentNode);
                                goto ReloadNode;
                            }
                            i++;
                            
                        }
                        break;
                    }
                    foreach (XmlNode node1 in NodeList)
                    {
                        foreach (XmlNode node2 in node1)
                        {
                            columnCount++;
                        }
                    }
                    if (dataGridView1.Rows.Count - 1 > columnCount)
                    {
                        foreach (XmlNode node1 in NodeList)
                        {
                            for (int k = columnCount; k < dataGridView1.Rows.Count - 1; k++)
                            {
                                XmlElement TableColumn = XmlTable.CreateElement(dataGridView1.Rows[k].Cells[0].Value.ToString());
                                XmlText TableColumnText = XmlTable.CreateTextNode("");
                                TableColumn.AppendChild(TableColumnText);
                                node1.AppendChild(TableColumn);
                            }
                        }
                        

                    }
                    
                    if (newTableName != CtTableName)
                    {
                        NodeList = XmlTable.SelectNodes("Root"+CtTableName);
                        XmlNode RootNode = XmlTable.SelectSingleNode("Root" + CtTableName);
                        XmlElement NewRootNode = XmlTable.CreateElement("Root" + newTableName);
                        NewRootNode.InnerXml = RootNode.InnerXml;
                        XmlTable.ReplaceChild(NewRootNode, RootNode);
                        string UpdateTableXml = XmlTable.InnerXml;
                        UpdateTableXml = UpdateTableXml.Replace("<"+CtTableName + ">", "<"+newTableName + " >");
                        UpdateTableXml = UpdateTableXml.Replace("</" + CtTableName + ">", "</" + newTableName + ">");
                        XmlTable.InnerXml = UpdateTableXml;
                        XmlTable.Save(CTServerPath + "\\" + newTableName + ".xml");
                        File.Delete(CTServerPath + "\\" + CtTableName + ".xml");
                        MessageBox.Show("Table Updated Successfully!");
                        this.Close();
                    }
                    else
                    {
                        XmlTable.Save(CTServerPath + "\\" + CtTableName + ".xml");
                        MessageBox.Show("Table Updated Successfully!");
                        this.Close();
                    }

                }
                else
                {
                    MessageBox.Show("Table Update Failed!");
                    return;
                }

            }
            else
            {
                MessageBox.Show("Table Update Failed!");
                return;
            }
            //sveBtn_Click(sender, e);

        }

        private void delTable_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(CTServerPath))
            {
                if (File.Exists(CTServerPath + "\\" + CtTableName + ".xml"))
                {                    
                    var result = MessageBox.Show("Do you really want to delete " + CtTableName + " Table","Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result == DialogResult.Yes)
                    {
                        File.Delete(CTServerPath + "\\" + CtTableName + ".xml");
                        MessageBox.Show(CtTableName + " is Deleted!");
                        this.Close();
                    }
                    else if (result == DialogResult.No)
                    {
                        this.Close();
                    }
                }
                else
                {
                    MessageBox.Show("Table is missing!");
                    return ;
                }
            }
            else
                return ;
        }

    }
}
